export default class SocketService {
    /**
     * 单例
     */

    static instance = null
    static get Instance() {
        if (!this.instance) {
            this.instance = new SocketService()
        }
        return this.instance
    }

    //和服务器连接的socket对象
    ws = null

    //储存回调
    callBackMapping = {}

    connected = false
    sendReTryCount = 0
    connectReTryCount = 0


    //定义连接服务器
    connect() {
        //连接服务器
        if (!window.WebSocket) {
            return console.log("浏览器不支持websocket");
        } else {
            this.ws = new WebSocket('ws://localhost:9998');

            //连接成功
            this.ws.onopen = () => {
                console.log("连接服务器成功");
                this.connected = true
                this.connectReTryCount = 0
            }

            //连接失败
            this.ws.onclose = () => {
                console.log("连接服务器失败");
                this.connected = false
                this.connectReTryCount++
                setTimeout(() => {
                    this.connect()
                }, 500 * this.connectReTryCount)
            }
            //得到数据
            this.ws.onmessage = (msg) => {
                console.log("从服务器获取数据");
                // console.log(msg.data);
                const recvDAata = JSON.parse(msg.data);
                // console.log(recvDAata);
                const socketType = recvDAata.socketType
                //判断回调函数
                if (this.callBackMapping[socketType]) {
                    const action = recvDAata.action
                    if (action === "getData") {
                        const realData = JSON.parse(recvDAata.data)
                        console.log("realData", realData);
                        this.callBackMapping[socketType].call(this, realData)
                    } else if (action === "fullScreen") {
                        this.callBackMapping[socketType].call(this, recvDAata)
                    } else if (action === "themeChange") {
                        this.callBackMapping[socketType].call(this, recvDAata)
                    }
                }
            }
        }
    }

    registerCallBack(socketType, callBack) {
        this.callBackMapping[socketType] = callBack
    }
    unRegisterCallBack(socketType) {
        this.callBackMapping[socketType] = null
    }
    //发送数据
    send(data) {
        if (this.connected) {
            this.sendReTryCount = 0
            console.log("data", data);
            this.ws.send(JSON.stringify(data))
        } else {
            this.sendReTryCount++
            setTimeout(() => {
                this.send(data)
            }, 500 * this.sendReTryCount)
        }
    }
} 